package com.zx.mobile.filter;

import com.zx.map.service.SessionInfoService;
import com.zx.map.service.model.SessionInfoModel;
import com.zx.map.utils.MyBeanUtils;
import com.zx.mobile.MobileCommonHelper;
import com.zx.mobile.SessionHelper;
import com.zx.mobile.context.ApplicationContextUtil;
import com.zx.mobile.domain.MobileUserDomain;
import com.zx.platform.utils.AccountObjectSerializerUtil;
import com.zx.platform.utils.DateUtils;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 手机或app端 访问控制
 *
 * @author jefferry.lu
 */
public class SecurityMobileFilter extends HttpServlet implements Filter {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -7184005924528959301L;

	/**
	 * log
	 */
	private static Logger log = Logger.getLogger(SecurityMobileFilter.class);

	public void doFilter(ServletRequest request, ServletResponse response,
	                     FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String uri = req.getRequestURI();
		if (MobileFilterHelper.urlNotNeedFilter(uri)) {
			filterChain.doFilter(request, response);
			return;
		}

		// 如果获取到sessionId app端用户登录
		Object sessionId = request.getParameter("sessionId");
//		log.info("----------security mobile filter get sessionId-----------" + sessionId);
		if (null != sessionId) {
			// 当前由app调用均会上送sessionId 为避免登陆接口访问和页面加载方式不同 导致登陆后 应用服务器并没有session
			// 统一从数据库中获取
			// 并设置到本地session
			SessionInfoService sessionInfoService = (SessionInfoService) ApplicationContextUtil
					.getContext().getBean("sessionInfoService");
			SessionInfoModel model = new SessionInfoModel();
			model.setSessionId(sessionId.toString());
			List<SessionInfoModel> list = sessionInfoService
					.getListByModel(model);
			if (null != list && list.size() == 1) {
				SessionInfoModel temp = list.get(0);
				MobileUserDomain user = MyBeanUtils.jsonToBean(temp.getSessionInfo(), MobileUserDomain.class);
				user.setKeepKey(sessionId.toString());
				// 更新超时时间 默认一个小时
				temp.setExpireDate(DateUtils.addDateByHour(new Date(),
						MobileCommonHelper.SYSLOGINTIMEOUT));
				sessionInfoService.update(temp);

				req.getSession().setAttribute(SessionHelper.MOBILEUSER, user);
			} else {
				HttpServletResponse httpResponse = (HttpServletResponse) response;
				httpResponse.sendRedirect(req.getContextPath()
						+ "/jsp/mobile/sessionexpire.jsp");
				return;
			}
		}
		filterChain.doFilter(request, response);
		return;
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
